#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include "common.hpp"
#include "InetAddr.hpp"
#include "log.hpp"

void Usage(std::string proc)
{
    std::cerr << "Usage :" << proc << "service_ip  service_port" << std::endl;
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(ARGV_ERROR);
    }

    // 创建文件描述符。
    int sockfd = socket(AF_INET,SOCK_STREAM,0);

    if(sockfd < 0)
    {
        LogSpace::LOG(LogSpace::LogLevel::FATAL) << "Sock Fail!";
        ::exit(SOCK_ERROR);
    }

    InetAddrModule::InetAddr service(std::stoi(argv[1]),argv[2]);
    // 和Udp一样，没必要bind，但tcp需要connect。
    int n = connect(sockfd,(service.NetAddrPtr()),service.NetAddrLen());

    if(n < 0)
    {
        LogSpace::LOG(LogSpace::LogLevel::FATAL) << "Connect Fail!";
        exit(CONNECT_ERROR);
    }

    while(true)
    {
        // 客户端先写后读。
        std::string line;

        std::cout << "Please Enter#" << std::endl;

        std::getline(std::cin,line);

        write(sockfd,line.c_str(),line.size());

        char buffer[1024];
        ssize_t n = read(sockfd,buffer,sizeof(buffer));

        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}